package com.opensso.core.interceptor;

import com.opensso.core.enums.SessionEnum;
import com.opensso.core.tools.JwtToken;
import com.opensso.domain.entity.DomainPool;
import com.opensso.domain.service.DomainPoolSV;
import com.opensso.setting.entity.Setting;
import com.opensso.setting.service.SettingSV;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 对请求进行验证的地址，域名进行验证
 */
@Component
@Slf4j
public class VerifyInterceptor implements HandlerInterceptor {

    //域名池子
    @Resource
    private DomainPoolSV domainPoolSV;

    @Resource
    private SettingSV settingSV;

    /**
     * 拦截请求，并进行合法性验证
     * 1.验证请求callToken合法性
     * 2.获取token
     * 3.获取apikey相关授权信息
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.验证请求callToken合法性

        // 2.获取token
        String token = request.getHeader(SessionEnum.Authorization.name());
        if (StringUtils.isBlank(token)) {
            return false;
        }
        log.info("Verify Token >> " + token);

        //3.获取apikey相关授权信息
        String apiKey = request.getHeader(SessionEnum.ApiKey.name());
        if (StringUtils.isBlank(apiKey)) {
            return false;
        }
        DomainPool domainPool = domainPoolSV.loadByApiKey(apiKey);
        if (domainPool == null) {
            return false;
        }
        log.info("apiKey >> " + apiKey);


        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * <p>
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值，究竟哪个才是真正的用户端的真实IP呢？
     * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。
     * <p>
     * 如：X-Forwarded-For：192.168.1.110, 192.168.1.120, 192.168.1.130,
     * 192.168.1.100
     * <p>
     * 用户真实IP为： 192.168.1.110
     *
     * @return ip
     */
    public String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        log.info("来访ip >> " + ip);
        return ip;
    }


}